<?php

namespace plugin\ycMassage\app\api\controller;

use app\common\service\UploadService;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageAppointmentService;
use plugin\ycMassage\app\model\MassageCollectTechnician;
use plugin\ycMassage\app\model\MassageMch;
use plugin\ycMassage\app\model\MassageOrdersSub;
use plugin\ycMassage\app\model\MassageShop;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\model\MassageUserAddress;
use plugin\ycMassage\app\model\MassageUserTechnician;
use plugin\ycMassage\app\model\MassageUserTechnicianComment;
use plugin\ycMassage\app\model\MassageUserTechnicianQualifications;
use plugin\ycMassage\app\model\MassageUserTechnicianScheduling;
use plugin\ycMassage\app\model\MassageUserTechnicianStatistics;
use plugin\ycMassage\app\model\MassageUserTechnicianThumb;
use plugin\ycMassage\app\validate\MassageTechnician;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\NoticeType;
use plugin\ycMassage\utils\enum\State;
use plugin\ycMassage\utils\enum\TechnicianQualifications;
use plugin\ycMassage\utils\notice\Notice;
use plugin\ycMassage\utils\Str;
use support\Request;
use think\facade\Db;

class TechnicianController extends BaseController
{
    protected $noNeedLogin = ["list", "details"];
    public function list(Request $request)
    {
        $limit = $request->get('limit', 20);
        $page = $request->get('page');
        $keywords = $request->get('keywords');
        $saas_appid = $request->saas_appid;
        $uid = $request->uid;
        if (!$saas_appid) {
            $saas_appid = $request->appid;
        }
        $where = [
            't.saas_appid' => $saas_appid,
            't.examine' => Examine::YES['value']
        ];
        if ($keywords) {
            $where[] = ['t.name', 'like', "%{$keywords}%"];
        }
        if ($request->city) {
            $where[] = ['t.city_id', '=', $request->city];
        } elseif ($request->province) {
            $where[] = ['t.province_id', '=', $request->province];
        }
        $shop_id = $request->get('shop_id');
        if ($shop_id) {
            $where[] = ['t.work_shop_id', '=', $shop_id];
        }
        $order = "t.resting asc,t.create_time desc";
        $longitude = $request->longitude;
        $latitude = $request->latitude;
        if ($request->get('longitude') && $request->get('latitude')) {
            $longitude = floatval($request->get('longitude'));
            $latitude = floatval($request->get('latitude'));
        }
        $field = [
            't.uid as technician_id,t.work_shop_id,t.saas_appid,t.people_num,t.comment_num,t.latitude,t.longitude,t.collect_num,t.comment_grade,t.gender,t.age,t.resting',
            't.order_num + t.virtually_order_num as order_num',
            'u.headimg,u.nickname',
            's.title as shop_title'
        ];
        $model = MassageUserTechnician::alias('t')->where($where);
        $model->join('massage_user u', 'u.id = t.uid');
        $model->join('massage_shop s', 's.id = t.work_shop_id', 'left');
        if ($longitude && $latitude) {
            $range = $request->get('range');
            if ($range) {
                $model->having("`distance` <= {$range}");
            }
            $order = "t.resting asc,distance IS NULL,distance asc,t.comment_grade desc,t.create_time desc";
            $field[] = "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(({$latitude} * PI() / 180 - t.latitude * PI() / 180) / 2),2) + COS({$latitude} * PI() / 180) * COS(t.latitude * PI() / 180) * POW(SIN(({$longitude} * PI() / 180 - t.longitude * PI() / 180) / 2),2))) * 1000) AS distance";
        }
        $recommend = $request->get('recommend');
        if ($recommend) {
            $model->whereTime('t.recommend', '>', date('Y-m-d H:i:s'));
            $model->whereNotNull('t.recommend');
            $order = 't.recommend desc';
        }
        $service_id = $request->get('service_id');
        if ($service_id) {
            $model->join('massage_user_technician_service uts', "uts.uid = t.uid AND uts.service_id = {$service_id} AND uts.state=" . State::YES['value']);
        }
        $model->fieldRaw(implode(',', $field));
        $model->orderRaw($order);

        $individual_settlement = getHpConfig('individual_settlement', $saas_appid, 'technician');
        if (!$individual_settlement) {
            $model->whereNotNull('t.work_mch_id');
            $model->whereNotNull('t.work_shop_id');
        }
        $startDay = strtotime(date('Y-m-d') . ' 00:00:00');
        $endTime = time();
        if ($page) {
            $listObj = $model->paginate([
                'list_rows' => $limit,
                'page' => $page
            ]);
        } else {
            $listObj = $model->limit($limit)->select();
        }
        $shop_title = MassageReplaceIndustryPersonnelName($saas_appid, '个人技师');
        $list = $listObj->each(function ($item) use ($request, $startDay, $endTime, $shop_title) {
            $SORT = 1000;
            $item->nickname = base64_decode($item->nickname);
            if (strpos($item->headimg, 'http') !== 0) {
                $item->headimg = UploadService::url($item->headimg);
            }
            if (!$item->shop_title) {
                $item->shop_title = $shop_title;
            }
            # 头像装饰：1，2，3，4
            $item->headimg_decoration = null;
            # 计算距离
            $item->distance_text = null;
            if ($item->distance !== null) {
                if ($item->distance > 1000) {
                    $item->distance_text = round($item->distance / 1000, 2) . 'km';
                } else {
                    $item->distance_text = round($item->distance) . 'm';
                }
            }
            # 计算排期
            $item->appointment = State::YES['value'];
            $SORT -= 1000;
            # 查询已开始的排期
            if(!$item->resting){
                $Scheduling = MassageUserTechnicianScheduling::where(['uid' => $item->technician_id, 'saas_appid' => $item->saas_appid])
                    ->whereBetweenTimeField('start_time', 'end_time')
                    ->whereRaw('(`appointment_time` IS NULL OR `appointment_time`<`end_time`)')
                    ->find();
                if ($Scheduling) {
                    if ($Scheduling->appointment_time) {
                        $item->appointment_time = MassageGetAppointmentTime($Scheduling->appointment_time);
                    } else {
                        $item->appointment_time = '随时可约';
                    }
                }
                if (!$item->appointment_time) {
                    # 查询未开始的排期
                    $Scheduling = MassageUserTechnicianScheduling::where(['uid' => $item->technician_id, 'saas_appid' => $item->saas_appid])
                        ->whereTime('start_time', '>=', $startDay)
                        ->whereTime('end_time', '>=', $endTime)
                        ->whereRaw("(`appointment_time` IS NULL OR `appointment_time` < `end_time`)")
                        ->find();
                    if ($Scheduling) {
                        if ($Scheduling->appointment_time) {
                            $item->appointment_time = MassageGetAppointmentTime($Scheduling->appointment_time);
                        } else {
                            $item->appointment_time = MassageGetAppointmentTime($Scheduling->start_time);
                        }
                    }
                }
            }
            if (!$item->appointment_time) {
                $item->appointment_time = '休息中';
                $item->appointment = State::NO['value'];
                $SORT += 1000;
            }
            $item->is_collect = 0;
            if ($request->uid) {
                $item->is_collect = MassageCollectTechnician::where(['technician_id' => $item->technician_id, 'uid' => $request->uid])->count();
                if ($item->is_collect) {
                    $SORT -= 10;
                }
            }
            $SORT -= floatval($item->comment_grade) * 100;
            $orderSub = MassageOrdersSub::where(['technician_id' => $item->technician_id])->order('id desc')->find();
            if ($orderSub && time() - strtotime($orderSub->create_time) < 3600 * 12) {
                $item->last_time = $orderSub->create_time;
                $SORT -= 10;
            }
            $item->sort = $SORT;
        });
        return $this->successRes($list);
    }
    public function details(Request $request)
    {
        $technician_id = $request->get('technician_id');
        $saas_appid = $request->saas_appid;
        if (!$saas_appid) {
            $saas_appid = $request->appid;
        }
        if (!$technician_id) {
            return $this->fail(MassageReplaceIndustryPersonnelName($saas_appid, '未找到技师信息'));
        }
        $where = [];
        $where['t.uid'] = $technician_id;
        $where['t.saas_appid'] = $saas_appid;
        $model = MassageUserTechnician::alias('t')->where($where);
        $model->join('massage_user u', 'u.id = t.uid');
        $model->join('massage_shop s', 's.id = t.work_shop_id', 'left');
        $field = [
            't.uid as technician_id,t.work_shop_id,t.saas_appid,t.people_num,t.comment_num,t.latitude,t.longitude,t.collect_num,t.work_meet,t.comment_grade,t.gender,t.age,t.resting',
            't.order_num + t.virtually_order_num as order_num',
            'u.headimg', 'u.nickname',
            's.title as shop_title'
        ];
        $model->field($field);

        $startDay = strtotime(date('Y-m-d') . ' 00:00:00');
        $endTime = time();
        $Find = $model->find();
        if (!$Find) {
            return $this->fail(MassageReplaceIndustryPersonnelName($saas_appid, '未找到技师信息'));
        }

        $Find->nickname = base64_decode($Find->nickname);
        if (strpos($Find->headimg, 'http') !== 0) {
            $Find->headimg = UploadService::url($Find->headimg);
        }
        if (!$Find->shop_title) {
            $Find->shop_title = MassageReplaceIndustryPersonnelName($saas_appid, '个人技师');
        }
        # 头像装饰：1，2，3，4
        $Find->headimg_decoration = null;
        # 计算距离
        $Find->distance = null;
        $Find->distance_text = null;
        if ($request->longitude && $request->latitude && $Find->latitude && $Find->longitude) {
            $Find->distance = MassageHaversineDistance($request->latitude, $request->longitude, $Find->latitude, $Find->longitude);
            if ($Find->distance > 1) {
                $Find->distance_text = round($Find->distance, 2) . 'km';
            } else {
                $Find->distance_text = round($Find->distance * 1000) . 'm';
            }
        }
        # 计算排期
        if(!$Find->resting){
            # 查询已开始的排期
            $Scheduling = MassageUserTechnicianScheduling::where(['uid' => $Find->technician_id, 'saas_appid' => $Find->saas_appid])
                ->whereBetweenTimeField('start_time', 'end_time')
                ->whereRaw('(`appointment_time` IS NULL OR `appointment_time`<`end_time`)')
                ->find();
            if ($Scheduling) {
                if ($Scheduling->appointment_time) {
                    $Find->appointment_time = MassageGetAppointmentTime($Scheduling->appointment_time);
                } else {
                    $Find->appointment_time = '随时可约';
                }
            }
            if (!$Find->appointment_time) {
                # 查询未开始的排期
                $Scheduling = MassageUserTechnicianScheduling::where(['uid' => $Find->technician_id, 'saas_appid' => $Find->saas_appid])
                    ->whereTime('start_time', '>=', $startDay)
                    ->whereTime('end_time', '>=', $endTime)
                    ->whereRaw("(`appointment_time` IS NULL OR `appointment_time` < `end_time`)")
                    ->find();
                if ($Scheduling) {
                    if ($Scheduling->appointment_time) {
                        $Find->appointment_time = MassageGetAppointmentTime($Scheduling->appointment_time);
                    } else {
                        $Find->appointment_time = MassageGetAppointmentTime($Scheduling->start_time);
                    }
                }
            }
        }
        if (!$Find->appointment_time) {
            $Find->appointment_time = '休息中';
            $Find->reservation_disabled = true;
        }
        $Find->thumbs = [];
        $thumbs = MassageUserTechnicianThumb::where(['uid' => $Find->technician_id, 'saas_appid' => $Find->saas_appid, 'examine' => Examine::YES['value']])->column('url');
        if (!empty($thumbs)) {
            $Find->thumbs = UploadService::url($thumbs);
        }
        $Find->is_collect = 0;
        if ($request->uid) {
            $Find->is_collect = MassageCollectTechnician::where(['technician_id' => $Find->technician_id, 'uid' => $request->uid])->count();
        }

        $where = [
            'comment.saas_appid' => $saas_appid,
            'comment.technician_id' => $Find->technician_id,
            'comment.show' => State::YES['value'],
            'comment.examine' => Examine::YES['value']
        ];
        $comment = MassageUserTechnicianComment::alias('comment')->where($where)
            ->join('massage_user u', 'u.id=comment.uid')
            ->field('comment.*,u.nickname,u.headimg')
            ->order('comment.grade desc,comment.id desc')
            ->limit(5)
            ->select()->each(function ($item) use ($saas_appid) {
                if ($item->anony) {
                    $item->nickname = '匿名用户';
                    $item->headimg = UploadService::url(getHpConfig('default_avatar', $saas_appid, 'user'));
                } else {
                    $item->nickname = base64_decode($item->nickname);
                    if (strpos($item->headimg, 'http') !== 0) {
                        $item->headimg = UploadService::url($item->headimg);
                    }
                }
            });
        $Find->comments = $comment->toArray();
        $Find->comments_count = MassageUserTechnicianComment::alias('comment')->where($where)->count();
        MassageUserTechnicianStatistics::browseNumInc($saas_appid, $Find->technician_id);
        $Find->qualifications = MassageUserTechnicianQualifications::where(['uid' => $Find->technician_id, 'saas_appid' => $request->saas_appid])->field('url')->select()->each(function ($item) {
            $item->style = [
                'width' => '100%',
            ];
        });
        return $this->successRes($Find);
    }
    public function info(Request $request)
    {
        $model = MassageUserTechnician::where(['uid' => $request->uid, 'saas_appid' => $request->saas_appid])->find();
        if ($model) {
            $MassageUser = MassageUser::where(['id' => $request->uid])->find();
            if ($MassageUser->realname) {
                $model['name'] = $MassageUser->realname;
            } else {
                $model['name'] = '未实名';
            }
            $model->thumb = MassageUserTechnicianThumb::where(['uid' => $request->uid, 'saas_appid' => $request->saas_appid])->field('id,url')->select()->toArray();
            $model->qualifications = MassageUserTechnicianQualifications::where(['uid' => $request->uid, 'saas_appid' => $request->saas_appid])->field('id,url')->select()->toArray();
            $model->recommendNum = MassageUserTechnician::where(['saas_appid' => $request->saas_appid])->whereNotNull('recommend')->whereTime('recommend', '>', date('Y-m-d H:i:s'))->count();
            return $this->successRes($model);
        }
        return $this->fail(MassageReplaceIndustryPersonnelName($request->saas_appid, '未找到技师信息'));
    }
    public function getServiceTime(Request $request)
    {
        $technician_id = $request->get('technician_id');
        $endTime = time();
        $Scheduling = MassageUserTechnicianScheduling::where(['uid' => $technician_id, 'saas_appid' => $request->saas_appid])
            ->whereTime('end_time', '>=', $endTime)
            ->order('start_time asc')
            ->select()->each(function ($item) {
                $item->matrix = MassageAppointmentService::createMatrix($item->id, $item->start_time, $item->end_time, MassageAppointmentService::RSERVATION_DURATION);
            });
        if ($Scheduling->isEmpty()) {
            return $this->fail('休息中');
        }
        return $this->successRes($Scheduling);
    }
    public function getDistance(Request $request)
    {
        $address_id = $request->get('address_id');
        $MassageUserAddress = MassageUserAddress::where(['id' => $address_id, 'saas_appid' => $request->saas_appid, 'uid' => $request->uid])->find();
        if (!$MassageUserAddress) {
            return $this->fail('地址不存在');
        }
        $technician_id = $request->get('technician_id');
        $MassageUserTechnician = MassageUserTechnician::where(['uid' => $technician_id, 'saas_appid' => $request->saas_appid])->find();
        if (!$MassageUserTechnician) {
            return $this->fail(MassageReplaceIndustryPersonnelName($request->saas_appid, '技师不存在'));
        }
        $distance = MassageHaversineDistance($MassageUserAddress->latitude, $MassageUserAddress->longitude, $MassageUserTechnician->latitude, $MassageUserTechnician->longitude);
        return $this->successRes(['distance' => round($distance * 1000, 2)]);
    }
    public function apply(Request $request)
    {
        $D = $request->post();
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        if (!$uid) {
            $saas_appid = $request->appid;
        }
        $D['age'] = intval($D['age']);
        $config = getHpConfig('', $request->appid, 'technician');
        if (isset($config['individual_settlement']) && !$config['individual_settlement'] && empty($D['mch_id']) && empty($D['shop_id'])) {
            return $this->fail('不允许个人入驻');
        }
        $MassageUser = MassageUser::where(['id' => $uid, 'saas_appid' => $saas_appid])->find();
        if (isset($config['force_realname']) && $config['force_realname'] && $MassageUser && !$MassageUser->realname) {
            return $this->fail('请先实名认证');
        }
        $validate = new MassageTechnician;
        $validate->remove('regions', $validate->rule['regions']);
        if (!empty($config['qualifications'])) {
            $qualifications = [];
            foreach ($config['qualifications'] as $key => $value) {
                $qualifications[] = TechnicianQualifications::getText($value)['text'];
            }
            $validate->append('qualifications', 'require|array|length:' . count($qualifications) . ',' . count($qualifications) + 1);
            $validate->message([
                'qualifications.require' => '请确认是否上传：' . implode('、', $qualifications),
                'qualifications.array' => '请确认是否上传：' . implode('、', $qualifications),
                'qualifications.length' => '请确认是否上传：' . implode('、', $qualifications),
            ]);
        }
        if (!$validate->check($D)) {
            return $this->fail($validate->getError());
        }
        Db::startTrans();
        try {
            $model = null;
            if ($uid) {
                $model = MassageUserTechnician::where(['uid' => $uid, 'saas_appid' => $saas_appid])->find();
                if (!$model) {
                    $model = new MassageUserTechnician;
                    $model->uid = $uid;
                    $model->saas_appid = $saas_appid;
                }
                $mobile = $D['mobile'];
                $userModel = MassageUser::where(['mobile' => $mobile, 'saas_appid' => $saas_appid])->find();
                if ($userModel) {
                    if ($userModel->id != $uid) {
                        throw new \Exception('手机号已绑定其他用户，请直接登录查看');
                    }
                } else {
                    $userModel = MassageUser::where(['id' => $uid, 'saas_appid' => $saas_appid])->find();
                    if (!$userModel->mobile) {
                        $userModel->mobile = $mobile;
                        $userModel->save();
                    }
                }
            } else {
                $mobile = $D['mobile'];
                $userModel = MassageUser::where(['mobile' => $mobile, 'saas_appid' => $saas_appid])->find();
                if ($userModel) {
                    throw new \Exception('手机号已注册账号，请直接登录查看');
                }
                $MassageUser = new MassageUser;
                $MassageUser->saas_appid = $saas_appid;
                $MassageUser->mobile = $mobile;
                $MassageUser->nickname = "游客" . Str::random(6, 1);
                $MassageUser->headimg = getHpConfig('web_url', null, 'system') . '/app/ycMassage/image/logo.png';
                $MassageUser->save();
                $model = new MassageUserTechnician;
                $model->uid = $MassageUser->id;
                $model->saas_appid = $saas_appid;
            }
            if (!empty($D['mch_id'])) {
                $MassageMch = MassageMch::where(['id' => $D['mch_id'], 'saas_appid' => $saas_appid])->find();
                if (!$MassageMch) {
                    throw new \Exception('商户不存在');
                }
                $model->mch_id = $MassageMch->id;
                $model->work_mch_id = $MassageMch->id;
            }
            if (!empty($D['shop_id'])) {
                $MassageShop = MassageShop::where(['id' => $D['shop_id'], 'saas_appid' => $saas_appid])->find();
                if (!$MassageShop) {
                    throw new \Exception('门店不存在');
                }
                $model->mch_id = $MassageShop->mch_id;
                $model->work_mch_id = $MassageShop->mch_id;
                $model->work_shop_id = $MassageShop->id;
                $MassageShop->people_num = Db::raw('people_num+1');
                $MassageShop->save();
            }
            $model->age = (int)$D['age'];
            $model->province_id = (int)$D['province_id'];
            $model->province = $D['province'];
            $model->city_id = (int)$D['city_id'];
            $model->city = $D['city'];
            $model->gender = $D['gender'];
            $model->mobile = $D['mobile'];
            $model->name = $D['name'];
            $model->work_meet = $D['work_meet'];
            $model->examine = Examine::WAIT['value'];
            $model->save();
            # 技师照片
            $MassageUserTechnicianThumb = new MassageUserTechnicianThumb;
            $thumb = [];
            foreach ($D['thumb'] as $key => $value) {
                $temp = [
                    'uid' => $model->uid,
                    'saas_appid' => $saas_appid,
                    'url' => $value['url'],
                ];
                if (isset($value['id'])) {
                    $temp['id'] = $value['id'];
                }
                krsort($temp);
                $thumb[] = $temp;
            }
            $MassageUserTechnicianThumb->saveAll($thumb);
            # 从业资格证
            $MassageUserTechnicianQualifications = new MassageUserTechnicianQualifications;
            $qualifications = [];
            foreach ($D['qualifications'] as $key => $value) {
                $temp = [
                    'uid' => $model->uid,
                    'saas_appid' => $saas_appid,
                    'url' => $value['url'],
                ];
                if (isset($value['id'])) {
                    $temp['id'] = $value['id'];
                }
                krsort($temp);
                $qualifications[] = $temp;
            }
            if (!empty($qualifications)) {
                $MassageUserTechnicianQualifications->saveAll($qualifications);
            }
            $notice = new Notice();
            $notice->saas_appid = $model->saas_appid;
            $notice->role = ['ADMIN'];
            $notice->type = NoticeType::WORK_ORDER['value'];
            $notice->setData([
                'service_name' => '技师入驻审核',
                'name' => $model->name . '(' . $model->uid . ')',
                'time' => date('Y-m-d H:i:s'),
            ]);
            $notice->send();
            Db::commit();
            return $this->success('申请成功,请等待审核');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
    }
    public function deleteTechnicianImage(Request $request)
    {
        $id = $request->post('id');
        $name = $request->post('name');
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        switch ($name) {
            case 'thumb':
                $model = MassageUserTechnicianThumb::where(['id' => $id, 'uid' => $uid, 'saas_appid' => $saas_appid])->find();
                break;
            case 'qualifications':
                $model = MassageUserTechnicianQualifications::where(['id' => $id, 'uid' => $uid, 'saas_appid' => $saas_appid])->find();
                break;
            default:
                return $this->fail('未找到图片');
                break;
        }
        if ($model) {
            $model->delete();
            return $this->success('删除成功');
        }
        return $this->fail('未找到图片');
    }
    public function statistics(Request $request)
    {
        $date = $request->get('date');
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $model = MassageUserTechnicianStatistics::where(['uid' => $uid, 'saas_appid' => $saas_appid]);
        switch ($date) {
            case 'yesterday':
                $model->whereDay('create_time', 'yesterday');
                break;
            case 'week':
                $model->whereWeek('create_time');
                break;
            case 'month':
                $model->whereMonth('create_time');
                break;
            case 'last_month':
                $model->whereMonth('create_time', 'last month');
                break;
            default:
                $model->whereDay('create_time');
                break;
        }
        $MassageUserTechnicianStatistics = $model->select();
        $data = [
            'order_num' => 0,
            'order_price' => 0,
            'duration' => 0,
            'new_customers' => 0,
            'commission' => 0,
            'browse_num' => 0,
        ];
        foreach ($MassageUserTechnicianStatistics as $item) {
            $data['order_num'] += $item->order_num;
            $data['order_price'] += $item->order_price;
            $data['duration'] += $item->duration;
            $data['new_customers'] += $item->new_customers;
            $data['commission'] += $item->commission;
            $data['browse_num'] += $item->browse_num;
        }
        return $this->successRes($data);
    }
    public function recommendExchange(Request $request)
    {
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $num = (int)$request->post('num');
        if ($num <= 0) {
            return $this->fail('兑换失败，兑换数量不能小于0');
        }
        if (MassageUserTechnician::where(['saas_appid' => $request->saas_appid])->whereNotNull('recommend')->whereTime('recommend', '>', date('Y-m-d H:i:s'))->count() >= 8) {
            return $this->fail('推荐位已满，请稍后再试');
        }
        $MassageUserTechnician = MassageUserTechnician::where(['uid' => $uid, 'saas_appid' => $saas_appid])->find();
        if (!$MassageUserTechnician) {
            return $this->fail('未找到技师信息');
        }
        $silver_num = $MassageUserTechnician->recommend_silver_num + ($MassageUserTechnician->recommend_gold_num * 5);
        $day = $silver_num / 5;
        if ($num > $day) {
            return $this->fail('兑换失败，您的推荐券数量不足');
        }
        if ($MassageUserTechnician->recommend > date('Y-m-d H:i:s')) {
            $MassageUserTechnician->recommend = date('Y-m-d H:i:s', strtotime("+{$num} day", strtotime($MassageUserTechnician->recommend)));
        } else {
            $MassageUserTechnician->recommend = date('Y-m-d H:i:s', strtotime("+{$num} day"));
        }
        $recommend_silver_num = floor($MassageUserTechnician->recommend_silver_num / 5);
        $num = $num - $recommend_silver_num;
        $MassageUserTechnician->recommend_silver_num = Db::raw('recommend_silver_num-' . ($recommend_silver_num * 5));
        if ($num > 0) {
            $MassageUserTechnician->recommend_gold_num = Db::raw('recommend_gold_num-' . $num);
        }
        if ($MassageUserTechnician->save()) {
            return $this->success('兑换成功');
        }
        return $this->fail('兑换失败');
    }
    public function shop(Request $request)
    {
        $saas_appid = $request->saas_appid;
        $uid = $request->uid;
        $MassageUserTechnician = MassageUserTechnician::where(['uid' => $uid, 'saas_appid' => $saas_appid])->find();
        if (!$MassageUserTechnician) {
            return $this->fail('未找到技师信息');
        }
        if ($MassageUserTechnician->work_mch_id) {
            $MassageMch = MassageMch::where(['id' => $MassageUserTechnician->work_mch_id, 'saas_appid' => $saas_appid])->find();
            $MassageMch->collect_num = 0;
            $MassageMch->people_num = 0;
            $MassageMch->comment_num = 0;
            $MassageMch->id = $MassageUserTechnician->work_shop_id;
            $MassageUserTechnician->mch = $MassageMch;
            if ($MassageUserTechnician->work_shop_id) {
                $MassageShop = MassageShop::where(['id' => $MassageUserTechnician->work_shop_id, 'saas_appid' => $saas_appid])->find();
                $MassageUserTechnician->shop = $MassageShop;
            }
        }
        return $this->successRes($MassageUserTechnician);
    }
    public function updateLocation(Request $request)
    {
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $latitude = $request->post('latitude');
        $longitude = $request->post('longitude');
        $model = MassageUserTechnician::where(['uid' => $uid, 'saas_appid' => $saas_appid])->find();
        if ($model) {
            $model->latitude = $latitude;
            $model->longitude = $longitude;
            $model->save();
            return $this->success('更新成功');
        }
        return $this->fail('未找到技师信息');
    }
    public function toggleResting(Request $request)
    {
        $uid=$request->uid;
        $saas_appid=$request->saas_appid;
        $model = MassageUserTechnician::where(['uid' => $uid, 'saas_appid' => $saas_appid])->find();
        if ($model) {
            $model->resting = $model->resting ? 0 : 1;
            $model->save();
            return $this->success('操作成功');
        }
        return $this->fail('未找到技师信息');
    }
}
